package org.spring.aicloud.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.spring.aicloud.entity.Comment;
import org.spring.aicloud.entity.Discuss;
import org.spring.aicloud.entity.DiscussSurpport;
import org.spring.aicloud.entity.User;
import org.spring.aicloud.service.ICommentService;
import org.spring.aicloud.service.IDiscussService;
import org.spring.aicloud.service.IDiscussSurpportService;
import org.spring.aicloud.service.IUserService;
import org.spring.aicloud.utils.AppVariable;
import org.spring.aicloud.utils.ResponseEntity;
import org.spring.aicloud.utils.SecurityUtil;
import org.spring.aicloud.vo.CommentVO;
import org.spring.aicloud.vo.DiscussVO;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


/**
 * @author yexiebao
 * @date 2025/5/20
 * 讨论表控制器
 */
@RestController
@RequestMapping("/discuss")
public class DiscussController {
    @Resource
    private IDiscussService discussService;
    @Resource
    private ThreadPoolTaskExecutor threadPool;
    @Resource
    private IUserService userService;
    @Resource
    private ICommentService commentService;
    @Resource
    private IDiscussSurpportService discussSurpportService;
    @Resource
    private KafkaTemplate kafkaTemplate;
    /**
     * 添加讨论
     * @param discuss 讨论对象
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity add(@Validated Discuss discuss) {
        discuss.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean saveResult= discussService.save(discuss);
        if(saveResult){
            return ResponseEntity.ok("success");
        }
        return ResponseEntity.error("保存失败,请重试！");
    }
    /**
     * 获取我的讨论列表
     * @return 讨论列表
     */
    @PostMapping("/getmylist")
    public ResponseEntity getMyList() {
        QueryWrapper<Discuss> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", SecurityUtil.getCurrentUser().getUid())
                    .orderByDesc("did");
        return ResponseEntity.ok(discussService.list(queryWrapper));
    }
    /**
     * 删除我的讨论
     * @return 讨论列表
     */
    @PostMapping("/deletemylist")
    public ResponseEntity deleteMyList(Long did){
        if(did==null||did<=0){
            return ResponseEntity.error("参数错误！");
        }
        boolean deleteResult = discussService.remove(Wrappers.lambdaQuery(Discuss.class)
                .eq(Discuss::getDid, did)
                .eq(Discuss::getUid,SecurityUtil.getCurrentUser().getUid()));
        if(deleteResult){
            return ResponseEntity.ok("success");
        }
        return ResponseEntity.error("删除失败,请重试！");
    }
    /**
     * 获取讨论详情
     * @param did 讨论id
     * @return 讨论详情
     */
    @PostMapping("/detail")
    public ResponseEntity detail(Long did) throws ExecutionException, InterruptedException {
        if(did==null||did<=0){
            return ResponseEntity.error("参数错误！");
        }
        Discuss discuss = discussService.getById(did);
        //判断一下获取的值是否为null
        if(discuss==null||discuss.getDid()<0){
            return ResponseEntity.error("获取内容失败！");
        }
        /**
         * 阅读量+1，异步线程（threadPool.submit()）中执行的，说明这个更新是异步的，不会马上影响内存中的 discuss 对象。
         */
        threadPool.submit(()->{
            //1.更新数据
            discussService.updateReadcount(did);
            //2.本地内存修改
            discuss.setReadcount(discuss.getReadcount()+1);
        });
        //并发任务一：查询dicuss中的username
        CompletableFuture<DiscussVO> usernameTask = CompletableFuture.supplyAsync(()->{
            DiscussVO discussVO = BeanUtil.toBean(discuss, DiscussVO.class);
            User user = userService.getById(discuss.getUid());
            if(user!=null&&user.getUid()>0){
                discussVO.setUsername(user.getUsername());
            }
            return discussVO;
        },threadPool);
        //并发任务二：查询discuss所对应的comment列表
        CompletableFuture<List<CommentVO>> commentListTask = CompletableFuture.supplyAsync(()->{
            //打印commentService.getCommentList(did)
            List<CommentVO> commentList = commentService.getCommentList(did);
            return commentList;
        },threadPool);
        CompletableFuture.allOf(usernameTask,commentListTask).join();
        HashMap<String,Object>result = new HashMap<>();
        result.put("discuss",usernameTask.get());
        result.put("commentList",commentListTask.get());
        return ResponseEntity.ok(result);
    }
    /**
     * 添加评论
     */
    @PostMapping("/addcomment")
    public ResponseEntity addComment(@Validated Comment comment){
        Long uid = SecurityUtil.getCurrentUser().getUid();
        comment.setUid(uid);
        boolean saveResult = commentService.save(comment);
        if(saveResult){
            return ResponseEntity.ok("success");
        }
        return ResponseEntity.error("添加失败,请重试！");
    }


    /**
     * 讨论表点赞事件
     */
    @PostMapping("/surpport")
    public ResponseEntity support(Long did) {
        if(did==null||did<=0){
            return ResponseEntity.error("参数错误！");
        }
        Long uid = SecurityUtil.getCurrentUser().getUid();
        kafkaTemplate.send(AppVariable.DISSCUS_SURPORT_TOPIC,did+"_"+uid);
        return ResponseEntity.ok("success");
    }

    /**
     * 监听Kafka点赞事件
     */
    @KafkaListener(topics = AppVariable.DISSCUS_SURPORT_TOPIC)
    public void listen(String event,  Acknowledgment ack){
        //1.查询当前用户是否已经点赞
        Long did = Long.parseLong(event.split("_")[0]);
        Long uid = Long.parseLong(event.split("_")[1]);
        boolean exist = discussSurpportService.exists(Wrappers.lambdaQuery(DiscussSurpport.class)
                .eq(DiscussSurpport::getDid,did)
                .eq(DiscussSurpport::getUid,uid));
        if(!exist){
            //2.修改讨论表总点赞数(discuss表）
            int updateResult = discussService.updateSupportcount(did);
            if(updateResult>0){
                //3.添加点赞记录（discussSurpport表）
                DiscussSurpport discussSurpport = new DiscussSurpport();
                discussSurpport.setDid(did);
                discussSurpport.setUid(uid);
                discussSurpportService.save(discussSurpport);
            }
        }
        //手动确认
        ack.acknowledge();
    }

    /**
     * 获取列表（分页）
     * @param page 页码
     * @param type 1:推荐；2:最新
     *
     */
    @PostMapping("/list")
    public ResponseEntity list(Integer page, Integer type){
        //1.参数校验
        if(page == null|| page<=0){
            page = 1;
        }
        if(type == null|| type<=0){
            type = 1;
        }
        QueryWrapper<Discuss>queryWrapper = new QueryWrapper<>();
        if(type == 1){//根据点赞数倒序
            queryWrapper.orderByDesc("supportcount");
        }else {//根据创建时间排序
            queryWrapper.orderByDesc("did");
        }
        //2.查询
        Page<Discuss> pageParam = discussService.page(new Page<>(page, AppVariable.PAGE_SIZE),queryWrapper);
        return ResponseEntity.ok(pageParam);
    }
}